package com.uidt.project.ptsj.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.uidt.common.utils.DictUtils;
import com.uidt.common.utils.StringUtils;
import com.uidt.framework.redis.RedisCache;
import com.uidt.project.ptsj.domain.CountItem;
import com.uidt.project.ptsj.domain.HouseInfo;
import com.uidt.project.ptsj.domain.PlaceInfo;
import com.uidt.project.ptsj.domain.PtsjRzrInfo;
import com.uidt.project.ptsj.mapper.HouseInfoMapper;
import com.uidt.project.ptsj.mapper.PlaceInfoMapper;
import com.uidt.project.ptsj.mapper.PtsjRzrInfoMapper;
import com.uidt.project.ptsj.service.IDataSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.uidt.common.utils.sign.SignUtil.createSign;

@Service
public class DataSyncServiceImpl implements IDataSyncService {

    @Autowired
    PlaceInfoMapper placeInfoMapper;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static String clientId = "6888bc08296546ec9c8a869b0973daae";
    public static String securityKey = "ac4e9a7c56db447ab1732f6ec2902925";
    public static String sm4key = "3b19ab2ce6f54bc3bf0926f9e8406154";
    static String serverUrl = "https://zsgawyf.police.zhoushan.gov.cn:17000/webapi";
    static String FY_ACTION = "/olp/shgz/v1/queryFy";
    static String DW_ACTION = "/olp/shgz/v1/queryDw";
    static String ZK_ACTION = "/olp/shgz/v1/queryZkWcn";

    static String zkQyrzl_ACTION = "/olp/shgz/v1/zkQyrzl";
    static String ZK_COUNT_ACTION = "/olp/shgz/v1/zkTotal";
    static String RZr_ACTION = "/olp/shgz/v1/queryRzr";
    @Autowired
    private HouseInfoMapper houseInfoMapper;

    @Autowired
    private PtsjRzrInfoMapper ptsjRzrInfoMapper;
    @Autowired
    private RedisCache redisCache;

    public static void main(String[] args) {
            DataSyncServiceImpl dataSyncService = new DataSyncServiceImpl();
//            dataSyncService.getCheckInTotal2();
//        JSONObject params = new JSONObject();
//        params.put("limit",1);
//        params.put("start",1);
//        System.out.println(new DataSyncServiceImpl().post(FY_ACTION,params));
    }

    @Override
    public int getCheckInTotal(){
        int total = 0;
        JSONObject result = get(ZK_ACTION);
        if (result.getIntValue("code") == 0) {
            total =result.getJSONObject("data").getIntValue("jrrzs");
        }
        return total;
    }

    @Override
    public String getCheckInTotal2(String gxdwdm){

        Map<String,String> map = redisCache.getCacheObject("PTSJ:CHECKIN:COUNTMAP");

        if(map != null){
            return map.get(gxdwdm);
        }else {
            map = new HashMap<>();
            DecimalFormat df = new java.text.DecimalFormat("#0.00");
            JSONObject result = get(zkQyrzl_ACTION+"?gxdwdm=3309");
            if (result.getIntValue("code") == 200) {
                JSONArray a = result.getJSONArray("data");
                for(int i = 0;i<a.size();i++){
                    JSONObject item = (JSONObject) a.get(i);
                    int all = item.getIntValue("value1");
                    int rzcount = item.getIntValue("value2");
                    if(all!=0 && rzcount!=0){
                        map.put(item.getString("pcsdm"), String.valueOf(df.format((double)rzcount*100/all)));
                    }else {
                        map.put(item.getString("pcsdm"), "0");
                    }
                }
            }
            JSONObject result2 = get(zkQyrzl_ACTION+"?gxdwdm=330999");
            if (result2.getIntValue("code") == 200) {
                JSONArray a = result2.getJSONArray("data");
                for(int i = 0;i<a.size();i++){
                    JSONObject item = (JSONObject) a.get(i);
                    int all = item.getIntValue("value1");
                    int rzcount = item.getIntValue("value2");
                    if(all!=0 && rzcount!=0){
                        map.put(item.getString("pcsdm"), String.valueOf(df.format((double)rzcount*100/all)));
                    }else {
                        map.put(item.getString("pcsdm"), "0%");
                    }
                }
            }
            redisCache.setCacheObject("PTSJ:CHECKIN:COUNTMAP",map,50, TimeUnit.MINUTES);
//            redisCache.getCacheObject("PTSJ:CHECKIN:COUNTMAP");
            return map.get(gxdwdm);
        }
    }

    @Override
    public List<CountItem> getGuestCountList() {
        List<CountItem> list = redisCache.getCacheObject("PTSJ:GUEST:LIST");
        if(list != null){
            logger.info(list.toString());
            return list;
        }
        list = new ArrayList<>();
        JSONObject result = get(ZK_COUNT_ACTION);
        logger.info(result.getString("data"));
        if (result.getIntValue("code") == 0) {
            String areacodes[] = DictUtils.getDictValues("ptsj_area_list").split(",");
            for (String area : areacodes) {
                CountItem countItem = new CountItem();
                countItem.setName(DictUtils.getDictLabel("ptsj_area_list",area));
                countItem.setCount(result.getJSONObject("data").getIntValue(area));
                list.add(countItem);
            }
        }

        redisCache.setCacheObject("PTSJ:GUEST:LIST", list,5, TimeUnit.MINUTES);
        return list;
    }


    /**
     * 同步入住信息
     */
    @Override
//    @PostConstruct
    public void syncLkrz() {

        // 首先获取本地数据库里，最新时间记录
        List<PtsjRzrInfo> rzrInfos = ptsjRzrInfoMapper.selectPtsjRzrInfoList(new PtsjRzrInfo());
        Date lastTime;

        Calendar calendar = Calendar.getInstance();
        if(rzrInfos==null || rzrInfos.size()==0){
            calendar.add(Calendar.MONTH,-1);
            lastTime = calendar.getTime();
        }else{
            lastTime = rzrInfos.get(0).getSjrzsj();
            calendar.setTime(lastTime);
            calendar.add(Calendar.MINUTE,-30);
            lastTime = calendar.getTime();
        }

        JSONObject params = new JSONObject();
        int start = 1;
        int limit = 100;
        params.put("start", start);
        params.put("limit", limit);
        JSONObject result = post(RZr_ACTION, params);
        if (result.getIntValue("code") == 0) {
            JSONArray list = result.getJSONObject("data").getJSONArray("list");
            int total = result.getJSONObject("data").getIntValue("count");
            int totalpage = total % limit == 0 ? total / limit : total / limit + 1;
            logger.info("{},{}",total,totalpage);
            Boolean flg = true;
            for (int k = start; k <= totalpage; k++) {
                if(!flg){
                    break;
                }
                logger.info("正在同步{}/{}",k,totalpage);
                if(k > 1){
                    params.put("start", k);
                    result = post(RZr_ACTION, params);
                    if(result.getIntValue("code") == 0) {
                        list = result.getJSONObject("data").getJSONArray("list");
                    }
                }
                for (int i = 0; i < list.size(); i++) {
                    try{
                        JSONObject data = list.getJSONObject(i);

                        //当查询到的记录时间，比我本地最新的记录时间还早晚30分钟之后，就停止插入
                        if(data.getDate("cjsj").getTime()<lastTime.getTime()){
                            flg=false;
                            break;
                        }else {
                            updateLkrz(list.getJSONObject(i));
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                        continue;
                    }
                }
            }
        }else{
            logger.error("{},{}",result.getIntValue("code"),result.getString("msg"));
        }
    }

    private void updateLkrz(JSONObject data){
        String id = data.getString("rzzkbh");//入住主键
        String fydjbh = data.getString("fydjbh");//房源登记编号
        Date yyrzsj = data.getDate("yyrzsj");//预约入住时间
        Date yytfsj = data.getDate("yytfsj");//预约退房时间
        Date sjrzsj = data.getDate("sjrzsj");//实际入住时间
        Date sjtfsj = data.getDate("sjtfsj");//实际退房时间
        Date cjsj = data.getDate("cjsj");//对方采集时间
        String zkxm = data.getString("zkxm");//住客姓名
        String zksjhm = data.getString("zksjhm");// 住客手机号码


        PtsjRzrInfo rzrInfo = ptsjRzrInfoMapper.selectPtsjRzrInfoById(id);
        boolean isNew = rzrInfo == null;
        if (isNew) {
            rzrInfo = new PtsjRzrInfo();
        }
//        PtsjRzrInfo rzrInfo = new PtsjRzrInfo();
        rzrInfo.setId(id);
        rzrInfo.setFydjbh(fydjbh);
        rzrInfo.setYyrzsj(yyrzsj);
        rzrInfo.setYytfsj(yytfsj);
        rzrInfo.setSjrzsj(sjrzsj);
        rzrInfo.setSjtfsj(sjtfsj);
        rzrInfo.setCjsj(cjsj);
        rzrInfo.setZkxm(zkxm);
        rzrInfo.setZksjhm(zksjhm);
        rzrInfo.setCreateTime(new Date());

        if(isNew){
            ptsjRzrInfoMapper.insertPtsjRzrInfo(rzrInfo);
        }else{
            rzrInfo.setUpdateTime(new Date());
            ptsjRzrInfoMapper.updatePtsjRzrInfo(rzrInfo);
        }
    }





    /**
     * 同步场所信息
     */
    @Override
    public void syncPlaceInfo() {
        JSONObject params = new JSONObject();
        int start = 1;
        int limit = 100;
        params.put("start", start);
        params.put("limit", limit);
        JSONObject result = post(DW_ACTION, params);
        if (result.getIntValue("code") == 0) {
            JSONArray list = result.getJSONObject("data").getJSONArray("list");
            int total = result.getJSONObject("data").getIntValue("count");
            int totalpage = total % limit == 0 ? total / limit : total / limit + 1;
            logger.info("{},{}",total,totalpage);
            for (int k = start; k <= totalpage; k++) {
                logger.info("正在同步{}/{}",k,totalpage);
                if(k > 1){
                    params.put("start", k);
                    result = post(DW_ACTION, params);
                    if(result.getIntValue("code") == 0) {
                        list = result.getJSONObject("data").getJSONArray("list");
                    }
                }
                for (int i = 0; i < list.size(); i++) {
                    JSONObject data = list.getJSONObject(i);
//                    if("2".equals(data.getString("fyjyzt"))){
                        // 只有当经营状态是2的时候，才入库
                        updateDwxx(list.getJSONObject(i));
//                    }

                }
            }
        }else{
            logger.error("{},{}",result.getIntValue("code"),result.getString("msg"));
        }
    }

    //[{"jydwmc":"舟山市星期八度假酒店管理有限公司","jyrdjbh":"00abfcf0-1c01-4b7d-8df2-57f757c1296f","jyrxm":"金荣星","jydwtyxydm":"91330900MAD852CD3T","jyrsjhm":"18768005678","jylx":"1","jydz":"朱家尖街道青山路80号"}
    private void updateDwxx(JSONObject data){
        String placeName = data.getString("jydwmc");//经营单位名称
        String placeCode = data.getString("jyrdjbh");//经营单位编号
        String ownerName = data.getString("jyrxm");//经营人姓名
        String certNumber = data.getString("jydwtyxydm");//单位信用代码
        String phone = data.getString("jyrsjhm");//经营人电话
        String ownerType = data.getString("jylx");//经营类型
        String status = data.getString("fyjyzt");// 经营状态
        String address = data.getString("jydz");//场所地址
        String jurisdictions = DictUtils.getDictLabel("ptsj_jurisdiction",data.getString("gxdwdm"));//管辖单位代码
        String gxdwdm = data.getString("gxdwdm");

        PlaceInfo placeInfo = placeInfoMapper.selectPlaceInfoByPlaceCode(placeCode);
        boolean isNew = placeInfo == null;
        if (isNew) {
            placeInfo = new PlaceInfo();
        }
        placeInfo.setPlaceCode(placeCode);
        placeInfo.setPlaceName(placeName);
//        placeInfo.setStars(1L);
        placeInfo.setOwnerName(ownerName);
        placeInfo.setCertNumber(certNumber);
        placeInfo.setPhone(phone);
        placeInfo.setOwnerType(ownerType);
        placeInfo.setAddress(address);
        placeInfo.setGxdwdm(gxdwdm);
        placeInfo.setStatus(status);
        placeInfo.setJurisdictions(jurisdictions);
        if(isNew && "2".equals(status)){
            placeInfo.setCreatedTime(new Date());
            placeInfoMapper.insertPlaceInfo(placeInfo);
        }else{
            placeInfo.setUpdateTime(new Date());
            placeInfoMapper.updatePlaceInfo(placeInfo);
        }
    }

    /**
     * 同步房间信息
     */
    @Override
    public void syncRoomInfo() {
        JSONObject params = new JSONObject();
        int start = 1;
        int limit = 100;
        params.put("start", start);
        params.put("limit", limit);
        JSONObject result = post(FY_ACTION, params);
        if (result.getIntValue("code") == 0) {
            JSONArray list = result.getJSONObject("data").getJSONArray("list");
            int total = result.getJSONObject("data").getIntValue("count");
            int totalpage = total % limit == 0 ? total / limit : total / limit + 1;
            logger.info("{},{}",total,totalpage);
            for (int k = start; k <= totalpage; k++) {
                logger.info("正在同步{}/{}",k,totalpage);
                if(k > 1){
                    params.put("start", k);
                    result = post(FY_ACTION, params);
                    if(result.getIntValue("code") == 0) {
                        list = result.getJSONObject("data").getJSONArray("list");
                    }
                }
                for (int i = 0; i < list.size(); i++) {
                    JSONObject data = list.getJSONObject(i);
//                    if("2".equals(data.getString("fyjyzt"))){
                        updateFyxx(list.getJSONObject(i));
//                    }

                }
            }
        }else{
            logger.error("{},{}",result.getIntValue("code"),result.getString("msg"));
        }
    }

    private void updateFyxx(JSONObject fyxx){
        String placeCode = fyxx.getString("fyjyrbh");//场所编号
        String roomName = fyxx.getString("fymc");//房源名称
        String jurisdictions = DictUtils.getDictLabel("ptsj_jurisdiction",fyxx.getString("gxdwdm"));//管辖单位代码
        String gxdwdm = fyxx.getString("gxdwdm");
        String status = fyxx.getString("fyjyzt");//房源经营状态
        String address = fyxx.getString("fywzdz");//房源地址
        String houseCode = fyxx.getString("fydjbh");//房源码

        String fyshzt = fyxx.getString("fyshzt");//房源审核状态

        HouseInfo houseInfo = houseInfoMapper.selectHouseInfoByHouseCode(houseCode);
        boolean isNew = houseInfo == null;
        if (isNew) {
            houseInfo = new HouseInfo();
        }
        // 根据场所编号获取场所信息
        PlaceInfo placeInfo = placeInfoMapper.selectPlaceInfoByPlaceCode(placeCode);
        if(placeInfo!=null){
            houseInfo.setPlaceName(placeInfo.getPlaceName());
        }

        houseInfo.setHouseCode(houseCode);
        houseInfo.setPlaceCode(placeCode);
        houseInfo.setRoomName(roomName);
        houseInfo.setStatus(status);
        houseInfo.setHouseType("1");
//        houseInfo.setCardstatus("0");
        houseInfo.setAddress(address);
        houseInfo.setGxdwdm(gxdwdm);
        houseInfo.setGxdwmc(jurisdictions);
        if(isNew && "2".equals(status) &&"3".equals(fyshzt)){
            houseInfo.setCreatedTime(new Date());
            houseInfoMapper.insertHouseInfo(houseInfo);
        }else{
            if(!"3".equals(fyshzt)){
                houseInfo.setStatus("99");
            }
            houseInfo.setUpdateTime(new Date());
            houseInfoMapper.updateHouseInfo(houseInfo);
        }
    }

    private JSONObject get(String action) {
        JSONObject signParams = new JSONObject();
        signParams.put("clientId", clientId);
        signParams.put("timestamp", System.currentTimeMillis());
        signParams.put("salt", IdUtil.simpleUUID());
        String sign = createSign(signParams.toJSONString(), securityKey);

        System.out.println("\n" + serverUrl + "\n" + action + "\n" + sign);
        HttpResponse response = HttpRequest.get(serverUrl + action)
                .header("sign", sign)
                .header("jsonStr", signParams.toJSONString())
                .execute();
        if (response.isOk() && StrUtil.isNotBlank(response.body())) {
            return JSONObject.parseObject(response.body());
        }
        return null;
    }

    private JSONObject post(String action, JSONObject params) {
        JSONObject signParams = new JSONObject();
        signParams.put("clientId", clientId);
        signParams.put("timestamp", System.currentTimeMillis());
        signParams.put("salt", IdUtil.simpleUUID());
        String sign = createSign(signParams.toJSONString(), securityKey);

        System.out.println("\n" + serverUrl + "\n" + action + "\n" + sign);
        HttpResponse response = HttpRequest.post(serverUrl + action)
                .header("sign", sign)
                .header("jsonStr", signParams.toJSONString())
                //请求参数
                .body(params.toString())
                .execute();
        if (response.isOk() && StrUtil.isNotBlank(response.body())) {
            return JSONObject.parseObject(response.body());
        }
        System.out.println(response.body());
        return null;
    }


}
